package com.okcl.manager.utils;

import com.okcl.model.entity.system.SysMenu;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 菜单工具类
 */
@UtilityClass
public class MenuHelper {
    /**
     * 构建菜单树
     *
     * @param sysMenuList
     * @return
     */
    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        List<SysMenu> tree = new ArrayList<>();
        sysMenuList.forEach(treeNode -> {
            if (treeNode.getParentId() == 0L) {
                tree.add(findChildren(treeNode, sysMenuList));
            }
        });
        return tree;
    }

    /**
     * 查找子节点
     *
     * @param treeNode 当前节点
     * @param all      所有节点
     * @return sysMenu 树节点
     */
    private SysMenu findChildren(SysMenu treeNode, List<SysMenu> all) {
        // 确保 children 不为 null
        treeNode.setChildren(Optional.ofNullable(treeNode.getChildren())
                .orElse(new ArrayList<>()));
        // 查找所有子节点并添加到当前节点
        List<SysMenu> children = all.stream()
                .filter(sysMenu -> sysMenu.getParentId().equals(treeNode.getId()))
                .map(sysMenu -> findChildren(sysMenu, all))
                .toList();
        treeNode.getChildren().addAll(children);
        return treeNode;
    }
}
